﻿using System.Text.RegularExpressions;

namespace Neoit.Utils.TemplateParser
{
    /// <summary>
    /// parse eg: ${name} or ${list[0].name}
    /// </summary>
    public class ParseVar
    {
        /// <summary>
        /// hi ${name} > hi jack
        /// propertyName ignore case and only support property, not methods
        /// </summary>
        public static string Parse<T>(string template, T data)
        {
            if (string.IsNullOrEmpty(template) || data == null) return template;
            var pattern = @"\$\{(.*?)\}"; // ${name} or ${list[0].name}
            var matches = Regex.Matches(template, pattern);

            foreach (Match match in matches)
            {
                var placeholder = match.Value; // e.g., ${title}
                var propertyPath = match.Groups[1].Value.Replace(" ", ""); // e.g., title or list[0].name
                object value;
                try
                {
                    value = ParseCommon.GetValueByPath(data, propertyPath);
                }
                catch
                {
                    value = string.Empty;
                }
                template = template.Replace(placeholder, value?.ToString() ?? string.Empty);
            }
            return template;
        }
    }
}
